﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mani.Common.Security;
using RastinArgham.CRM.Business;
using Mani.Common;
using System.IO;
using System.Text;

namespace RastinArgham.CRM.Web
{
    public partial class advance_search : System.Web.UI.Page
    {
        public ISecurityManager securityManager { get; set; }
        public CRMRepository crmRepository { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (securityManager == null)
            {
                securityManager = new SecurityManager();
                securityManager.authProvider = new WebAuthorizationProvider();
            }

            if (crmRepository == null)
                crmRepository = new CRMRepository();

            if (!securityManager.IsActionPermitted("advanced_search"))
                Response.Redirect("~/access_denied.aspx");

            if (!securityManager.IsActionPermitted("advanced_search_all"))
            {
                ddlAccountOwner.Enabled = false;
                ddlAccountManagers.Enabled = false;
            }

            if (!Page.IsPostBack)
            {
                LoadUsers();
                LoadCities();
                LoadProducts();
                LoadServices();
                LoadCancelationReasons();
                LoadServiceWorkflowStates();
                LoadOrderWorkflowStates();
                LoadLeadSources();
            }
        }

        private void LoadLeadSources()
        {
            ddlLeadSource.DataSource = crmRepository.GetLeadSources();
            ddlLeadSource.DataBind();
        }

        private void LoadServiceWorkflowStates()
        {
            ddlServiceOrderStatus.DataSource = (new ServiceOrderWorkflow()).GetStates();
            ddlServiceOrderStatus.DataBind();
        }

        private void LoadOrderWorkflowStates()
        {
            ddlProductOrderStatus.DataSource = (new ProductOrderWorkflow()).GetStates();
            ddlProductOrderStatus.DataBind();
        }

        private void LoadCancelationReasons()
        {
            ddlCancelationReason.DataSource = crmRepository.GetCancelationReasons();
            ddlCancelationReason.DataBind();
        }

        private void LoadServices()
        {
            ddlServiceId.DataSource = crmRepository.GetServices();
            ddlServiceId.DataBind();
        }

        private void LoadProducts()
        {
            ddlProductId.DataSource = crmRepository.GetProducts();
            ddlProductId.DataBind();
        }

        private void LoadCities()
        {
            ddlCity.DataSource = crmRepository.GetCities();
            ddlCity.DataBind();
        }

        private void LoadUsers()
        {
            List<aspnet_Users> users = securityManager.GetUsers();
            ddlAccountManagers.DataSource = users;
            ddlAccountManagers.DataBind();

            ddlAccountOwner.DataSource = users;
            ddlAccountOwner.DataBind();
        }

        protected void gvOrders_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvOrders.PageIndex = e.NewPageIndex;
            Search("gridview");
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Search("gridview");
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            Search("excel");
        }

        private void Search(string output)
        {
            int? serviceId = null;
            int? productId = null;
            int? cityId = null;
            Guid? accountManagerId = null;
            Guid? accountOwner = null;
            int? contactType = null;
            int? workflowStateId = null;
            int? cancelationReason = null;
            int contactId = -1;
            int? final_contact_id = null;
            int? leadSourceId = null;
            int? orderType = null;

            if (ddlOrderType.SelectedValue != "-1")
                orderType = Convert.ToInt32(ddlOrderType.SelectedValue);

            if (ddlServiceId.SelectedValue != "-1")
                serviceId = Convert.ToInt32(ddlServiceId.SelectedValue);

            if (ddlProductId.SelectedValue != "-1")
                productId = Convert.ToInt32(ddlProductId.SelectedValue);

            if (ddlCity.SelectedValue != "-1")
                cityId = Convert.ToInt32(ddlCity.SelectedValue);

            if (ddlAccountManagers.SelectedValue != "-1")
                accountManagerId = Guid.Parse(ddlAccountManagers.SelectedValue);

            if (ddlAccountOwner.SelectedValue != "-1")
                accountOwner =Guid.Parse(ddlAccountOwner.SelectedValue);

            if (ddlContactType.SelectedValue != "-1")
                contactType = Convert.ToInt32(ddlContactType.SelectedValue);

            if (!securityManager.IsActionPermitted("advanced_search_all"))
            {
                accountOwner = securityManager.authProvider.GetCurrentUser().UserId;
            }

            if (ddlServiceOrderStatus.SelectedValue != "-1")
                workflowStateId = Convert.ToInt32(ddlServiceOrderStatus.SelectedValue);
            else if (ddlProductOrderStatus.SelectedValue != "-1")
                workflowStateId = Convert.ToInt32(ddlProductOrderStatus.SelectedValue);

            if (ddlCancelationReason.SelectedValue != "-1")
                cancelationReason = Convert.ToInt32(ddlCancelationReason.SelectedValue);

            if (ddlLeadSource.SelectedValue != "-1")
                leadSourceId = Convert.ToInt32(ddlLeadSource.SelectedValue);

            if (!String.IsNullOrEmpty(txtContactId.Text) && Int32.TryParse(txtContactId.Text, out contactId))
                final_contact_id = contactId;

            List<Order> result = crmRepository.AdvancedSearch (
                txtContactTitle.Text,
                txtMobinReference.Text,
                accountManagerId,
                cityId,
                contactType,
                productId,
                serviceId,
                txtServiceStartDateBegin.Text.ToDateTime(),
                txtServiceStartDateEnd.Text.ToDateTime(),
                txtServiceBilledUptoBegin.Text.ToDateTime(),
                txtServiceBilledUptoEnd.Text.ToDateTime(),
                txtFinancialReferenceNumber.Text,
                txtInstaller.Text,
                txtInvoiceNumber.Text,
                accountOwner,
                workflowStateId,
                cancelationReason,
                txtMarketer.Text,
                final_contact_id,
                txtPaymentCode.Text,
                txtSubID.Text,
                leadSourceId, 
                orderType,
                txtOrderDateFrom.Text.ToDateTime(),
                txtOrderDateTo.Text.ToDateTime()
            );

            lblCount.Text = result.Count().ToString();

            if (output == "gridview")
            {
                gvOrders.Visible = true;
                gvOrders.DataSource = result;
                gvOrders.DataBind();
            }
            else if (output == "excel")
            {
                gvOrders.Visible = false;
                string temp_path = "~/tmp";
                ExportToExcel(result, temp_path);
            }
            else if (output == "excel_all_fields")
            {
                gvOrders.Visible = false;
                string temp_path = "~/tmp";
                ExportAllToExcel(result, temp_path);
            }                                                   
                                       
        }

        public void ExportAllToExcel(List<Order> orders, string tempDirectory)
        {
            ExportToExcel ee = new Mani.Common.ExportToExcel();
            string path = tempDirectory + "/" + Guid.NewGuid() + ".xls";
            StringBuilder ExcelContent = new StringBuilder();

            ExcelContent.Append(ee.InitializeExcel(Server.MapPath("~/Styles.config")));
            ExcelContent.Append(ee.StartWorkSheet(1));
            ExcelContent.Append(ee.StartTable());
            ExcelContent.Append(ee.StartRow());

            ExcelContent.Append(ee.NewCell("کد"));
            ExcelContent.Append(ee.NewCell("عنوان شخص"));
            ExcelContent.Append(ee.NewCell("نوع شخص"));
            ExcelContent.Append(ee.NewCell("نام شهر"));
            ExcelContent.Append(ee.NewCell("آدرس"));
            ExcelContent.Append(ee.NewCell("شماره تلفن همراه"));
            ExcelContent.Append(ee.NewCell("شماره تلفن"));
            ExcelContent.Append(ee.NewCell("کد پستی"));
            ExcelContent.Append(ee.NewCell("تصویر مدرک سرویس"));
            ExcelContent.Append(ee.NewCell("تصصویر مدرک شناسایی"));
            ExcelContent.Append(ee.NewCell("تصویر قبض"));

            ExcelContent.Append(ee.NewCell("تاریخ ایجاد کاربر"));
            ExcelContent.Append(ee.NewCell("بازاریاب"));
            ExcelContent.Append(ee.NewCell("شماره رهگیری مبین"));
            ExcelContent.Append(ee.NewCell("نام سرویس"));
            ExcelContent.Append(ee.NewCell("تاریخ شروع سرویس"));
            ExcelContent.Append(ee.NewCell("تاریخ پایان سرویس"));
            ExcelContent.Append(ee.NewCell("نام نصاب"));
            ExcelContent.Append(ee.NewCell("محصول"));

            ExcelContent.Append(ee.NewCell("DeptCode"));
            ExcelContent.Append(ee.NewCell("تاریخ ورود کالا به انبار"));
            ExcelContent.Append(ee.NewCell("ISDN"));
            ExcelContent.Append(ee.NewCell("شماره سریال کالا"));
            ExcelContent.Append(ee.NewCell("MAC"));
            ExcelContent.Append(ee.NewCell("Password"));
            ExcelContent.Append(ee.NewCell("کد پرداخت"));
            ExcelContent.Append(ee.NewCell("وضعیت کالا"));
            ExcelContent.Append(ee.NewCell("SubID"));

            ExcelContent.Append(ee.NewCell("مبلغ"));
            ExcelContent.Append(ee.NewCell("مالیات ( درصد )"));
            ExcelContent.Append(ee.NewCell("مبلغ کل ( ریال )"));
            ExcelContent.Append(ee.NewCell("وضعیت"));
            ExcelContent.Append(ee.NewCell("نام مسئول اکانت"));
            ExcelContent.Append(ee.NewCell("آخرین اپراتور"));

            ExcelContent.Append(ee.FinishRow());

            foreach (var o in orders)
            {
                ExcelContent.Append(ee.StartRow());

                ExcelContent.Append(ee.NewCell(o.OrderId.ToString()));
                ExcelContent.Append(ee.NewCell(o.ContactTitle));
                ExcelContent.Append(ee.NewCell(o.Contact.ContactTypeDescription));
                ExcelContent.Append(ee.NewCell(o.Contact.CityName));
                ExcelContent.Append(ee.NewCell(o.Contact.Address));
                ExcelContent.Append(ee.NewCell(o.Contact.MobilePhone));
                ExcelContent.Append(ee.NewCell(o.Contact.Phone));
                ExcelContent.Append(ee.NewCell(o.Contact.ZipCode));

                if (o.Contact.ContactTypeId == (int)ContactTypes.Personal)
                {
                    PersonalContact pc = o.Contact.PersonalContacts.FirstOrDefault();
                    if (pc.IdentityPhoto == null)
                        ExcelContent.Append(ee.NewCell("0"));
                    else
                        ExcelContent.Append(ee.NewCell("1"));

                    if (pc.ServicePhoto == null)
                        ExcelContent.Append(ee.NewCell("0"));
                    else
                        ExcelContent.Append(ee.NewCell("1"));

                    ExcelContent.Append(ee.NewCell("0"));
                }
                else
                {
                    CompanyContact cc = o.Contact.CompanyContacts.FirstOrDefault();
                    if( cc.IdPhoto == null )
                        ExcelContent.Append(ee.NewCell("0"));
                    else
                        ExcelContent.Append(ee.NewCell("1"));

                    if(cc.ServicePhoto == null)
                        ExcelContent.Append(ee.NewCell("0"));
                    else
                        ExcelContent.Append(ee.NewCell("1"));

                    if(cc.ChargePhoto == null)
                        ExcelContent.Append(ee.NewCell("0"));
                    else
                        ExcelContent.Append(ee.NewCell("1"));
                }

                ExcelContent.Append(ee.NewCell(o.Contact.CreateDate.ToJalali()));
                ExcelContent.Append(ee.NewCell(o.Contact.Marketer));
                ExcelContent.Append(ee.NewCell(o.Contact.MobinReference));
                ExcelContent.Append(ee.NewCell(o.ServiceName));
                ExcelContent.Append(ee.NewCell(o.ServiceStartDate.ToJalali()));
                ExcelContent.Append(ee.NewCell(o.ServiceExpirationDate.ToJalali()));
                ExcelContent.Append(ee.NewCell(o.Installer));

                ExcelContent.Append(ee.NewCell(o.ProductName));

                if (o.StockItems.Count > 0)
                {
                    StockItem s = o.StockItems.First();
                    ExcelContent.Append(ee.NewCell(s.DeptCode));
                    ExcelContent.Append(ee.NewCell(s.ImportDate.ToJalali()));
                    ExcelContent.Append(ee.NewCell(s.ISDN));
                    ExcelContent.Append(ee.NewCell(s.SerialNumber));
                    ExcelContent.Append(ee.NewCell(s.MAC));
                    ExcelContent.Append(ee.NewCell(s.Password));
                    ExcelContent.Append(ee.NewCell(s.PaymentCode));
                    ExcelContent.Append(ee.NewCell(s.StatusDescription));
                    ExcelContent.Append(ee.NewCell(s.SubID));
                }
                else
                {
                    ExcelContent.Append(ee.NewCell(""));
                    ExcelContent.Append(ee.NewCell(""));
                    ExcelContent.Append(ee.NewCell(""));
                    ExcelContent.Append(ee.NewCell(""));
                    ExcelContent.Append(ee.NewCell(""));
                    ExcelContent.Append(ee.NewCell(""));
                    ExcelContent.Append(ee.NewCell(""));
                    ExcelContent.Append(ee.NewCell(""));
                    ExcelContent.Append(ee.NewCell(""));
                }
 
                ExcelContent.Append(ee.NewCell(o.Price.ToString()));
                ExcelContent.Append(ee.NewCell(o.TaxPercent.ToString()));
                ExcelContent.Append(ee.NewCell(o.TotalPrice.ToString()));
                ExcelContent.Append(ee.NewCell(o.Status));
                ExcelContent.Append(ee.NewCell(securityManager.FindUserbyId(o.AccountManagerId).UserName));
                ExcelContent.Append(ee.NewCell(o.OperatorName));

                ExcelContent.Append(ee.FinishRow());
            }

            ExcelContent.Append(ee.FinishTable());
            ExcelContent.Append(ee.FinishWorksheet());
            ExcelContent.Append(ee.FinishFile());

            ee.SaveFile(ExcelContent, Server.MapPath(path));

            Response.Redirect(path);
        }

        public void ExportToExcel(List<Order> orders, string tempDirectory)
        {
            ExportToExcel ee = new Mani.Common.ExportToExcel();
            string path = tempDirectory + "/" + Guid.NewGuid() + ".xls";
            StringBuilder ExcelContent = new StringBuilder();

            ExcelContent.Append( ee.InitializeExcel(Server.MapPath("~/Styles.config")) );
            ExcelContent.Append( ee.StartWorkSheet(1));
            ExcelContent.Append( ee.StartTable());
            ExcelContent.Append( ee.StartRow());

            ExcelContent.Append( ee.NewCell("کد"));
            ExcelContent.Append( ee.NewCell("عنوان شخص"));
            ExcelContent.Append( ee.NewCell("محصول"));
            ExcelContent.Append( ee.NewCell("سریال محصول"));
            ExcelContent.Append(ee.NewCell("شناسه محصول"));
            ExcelContent.Append( ee.NewCell("نام سرویس"));
            ExcelContent.Append(ee.NewCell("تاریخ شروع سرویس"));
            ExcelContent.Append( ee.NewCell("مبلغ"));
            ExcelContent.Append( ee.NewCell("مالیات ( درصد )"));
            ExcelContent.Append( ee.NewCell("مبلغ کل ( ریال )"));
            ExcelContent.Append( ee.NewCell("وضعیت"));
            ExcelContent.Append( ee.NewCell("آخرین اپراتور"));

            ExcelContent.Append( ee.FinishRow());

            foreach (var o in orders)
            {
                ExcelContent.Append( ee.StartRow());

                ExcelContent.Append( ee.NewCell(o.OrderId.ToString()));
                ExcelContent.Append( ee.NewCell(o.ContactTitle));
                ExcelContent.Append( ee.NewCell(o.ProductName));
                ExcelContent.Append(ee.NewCell(o.Serial));
                ExcelContent.Append(ee.NewCell(o.SubID));
                ExcelContent.Append( ee.NewCell(o.ServiceName));
                ExcelContent.Append( ee.NewCell(o.ServiceStartDate.ToJalali()));
                ExcelContent.Append( ee.NewCell(o.Price.ToString()));
                ExcelContent.Append( ee.NewCell(o.TaxPercent.ToString()));
                ExcelContent.Append( ee.NewCell(o.TotalPrice.ToString()));
                ExcelContent.Append( ee.NewCell(o.Status));
                ExcelContent.Append( ee.NewCell(o.OperatorName));

                ExcelContent.Append( ee.FinishRow() );
            }

            ExcelContent.Append( ee.FinishTable() );
            ExcelContent.Append( ee.FinishWorksheet() );
            ExcelContent.Append( ee.FinishFile() );

            ee.SaveFile(ExcelContent, Server.MapPath(path));

            Response.Redirect(path);
        }

        protected void btnExportAll_Click(object sender, EventArgs e)
        {
            Search("excel_all_fields");
        }
    }
}